package com.cy.pj.sys.service.impl;

import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.util.PageUtil;
import com.cy.pj.sys.dao.SysUserDao;
import com.cy.pj.sys.dao.SysUserRoleDao;
import com.cy.pj.sys.pojo.SysUser;
import com.cy.pj.sys.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.security.provider.MD5;

import java.util.List;
import java.util.UUID;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;

    //@RequiresPermissions("sys:user:view")
    @Override
    public List<SysUser> findUsers(SysUser sysUser) {
        return sysUserDao.selectUsers(sysUser);
    }

    @Override
    public SysUser findById(Integer id) {
        SysUser sysUser=sysUserDao.selectById(id);//user,dept
        if(sysUser==null)
            throw new ServiceException("用户已不存在");
        //基于id查询用户对应的角色id
        List<Integer> roleIds = sysUserRoleDao.selectRoleIdsByUserId(id);//roles
        sysUser.setRoleIds(roleIds);
        return sysUser;
    }

    /**
     * @Transactional 此方法为一个事务切入点方法
     * @RequiresPermissions 描述方法时为一个授权切入点方法
     *      访问此方法时需授权，有权限则可以访问，无则抛出异常
     *      如何判定：在访问方法时，shiro框架底层会获取此方法
     *      的@RequiresPermissions 注解，获取个注解的权标识，
     *      后调用subject对象的
     *      checkPermissions(注解内权限标识)方法检测用户是否有权
     */
    //@RequiresPermissions("sys:user:update")
    @Transactional
    @Override
    public int saveUser(SysUser sysUser) {
        //保存用户自身信息

        //对密码进行加密
        String password=sysUser.getPassword();
        String salt= UUID.randomUUID().toString();
        SimpleHash simpleHash=
                //MD5加密，加密次数为1
                new SimpleHash("MD5",password,salt,1);
        password=simpleHash.toHex();//将加密算法转换为16进制（原2进制）
        sysUser.setPassword(password);
        sysUser.setSalt(salt);
        int rows=sysUserDao.insertUser(sysUser);
        //保存用户角色关系
        sysUserRoleDao.insertUserRoles(sysUser.getId(), sysUser.getRoleIds());
        return rows;
    }

    @Override
    public int updateUser(SysUser sysUser) {
        int rows=sysUserDao.insertUser(sysUser);
        if (rows==0)
            throw new ServiceException("人不在了");
        sysUserRoleDao.deleteByUserId(sysUser.getId());
        sysUserRoleDao.insertUserRoles(sysUser.getId(), sysUser.getRoleIds());
        return rows;
    }

    /**
     *
     * @param id
     * @param valid 状态
     * @return
     * 流程
     *  subject->SecurityManager->Authorize->Realm
     */
    @RequiresPermissions("sys:user:update")
    @Transactional
    @Override
    public int validById(Integer id, Integer valid) {
        //获取用户权限Set<String> permissions
        //获取此方法上的权限表示 -> sys:suer:update
        //判定用户的权限中是否包含方法上的权限表示 -> flag permissions.contains(sys:suer:update)
        //if(flag){}else{}
        //获取登录用户
        SysUser user=(SysUser) SecurityUtils.getSubject().getPrincipal();
        String modifiedUser=user.getModifiedUser();

        sysUserDao.validById(id, valid, modifiedUser);
        return 0;
    }
}
